<template>
    <div class="findpsw">
        <view-head></view-head>
        <div class="r-contain">
            <div class="r-c-c">
                <el-steps :active="active" finish-status="success">
                    <el-step title="填写用户名"></el-step>
                    <el-step title="验证身份"></el-step>
                    <el-step title="设置密码"></el-step>
                </el-steps>
                <el-form v-if="active==0" :model="ruleForm" status-icon :rules="ruleFormRules" ref="ruleForm" label-width="100px">
                    <el-form-item label-width="0px"  prop="userOrTel">
                        <el-input  v-model="ruleForm.userOrTel" placeholder="请输入用户名/手机号"></el-input>
                    </el-form-item>
                    <el-form-item label-width="0px"  prop="code">
                        <el-input v-model="ruleForm.code"  placeholder="请输入验证码"></el-input>
                    </el-form-item>
                    <el-form-item label-width="0px">
                        <random-code style="display: inline-block;" :identifyCode="identifyCode" @click="refreshCode()"></random-code>
                        <el-button style="position: absolute;right: 0px;" @click="refreshCode()" type="text" class="textbtn">看不清，换一张</el-button>
                    </el-form-item>
                    <el-form-item label-width="0px" style="text-align: center">
                        <el-button type="primary" @click="submitOneForm('ruleForm')">{{$t('btn_next')}}</el-button>
                    </el-form-item>
                </el-form>
                <el-form v-if="active==1" :model="ruleFormMobile" :rules="ruleFormMobileRules" ref="ruleFormMobile" status-icon  label-width="100px">
                    <el-form-item label-width="0px">
                        <el-input v-model="mobileStr" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label-width="0px"  prop="phone_code">
                        <el-input style="width: 164px" v-model="ruleFormMobile.phone_code"  :placeholder="$t('input_phone_code')"></el-input>
                        <SMSCode :disabled="disabled" ref="sms_mobile" :codeValue="username"  type="10" :prefix="mobilePrefix"></SMSCode>
                    </el-form-item>
                    <el-form-item label-width="0px" style="text-align: center">
                        <el-button type="primary" @click="submitSecondForm('ruleFormMobile')">{{$t('btn_next')}}</el-button>
                    </el-form-item>
                </el-form>

                <el-form v-if="active==2" :model="ruleFormPass" :rules="ruleFormPassRules" ref="ruleFormPass" status-icon  label-width="100px">
                    <el-form-item label-width="0px"  prop="pass">
                        <el-input type="password"  v-model="ruleFormPass.pass" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item label-width="0px"  prop="pass">
                        <el-input  type="password" v-model="ruleFormPass.checkpass" placeholder="请再次输入密码"></el-input>
                    </el-form-item>
                    <el-form-item label-width="0px" style="text-align: center">
                        <el-button type="primary" @click="submitThirdForm('ruleFormPass')">{{$t('btn_submit')}}</el-button>
                    </el-form-item>
                </el-form>

            </div>
        </div>
    </div>
</template>

<script>
    import Header from '@/components/__header.vue'
    import RandomCode from '@/components/randomCode.vue'
    import SMSCode from '@/components/SMSVcode.vue'
    export default {
        name: "findpsw",
        components: {
            'view-head':Header,
            "random-code":RandomCode,
            'SMSCode':SMSCode
        },
        data(){
            var codes = /^\d{6}$/;
            //校验密码 长度+1个数字+一个字母
            var passwords  =/^.*(?=.{6,20})(?=.*\d)(?=.*[a-z]{1,})/;
            //校验密码  长度+1个数字+一个字符
            var pattern = /^.*(?=.{6,20})(?=.*\d)(?=.*[!@#$%^&*?\(\)]).*$/;
            //校验密码 长度+一个字母+一个字符
            var patterns = /^.*(?=.{6,20})(?=.*[a-z]{2,})(?=.*[!@#$%^&*?\(\)]).*$/;
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请设置登陆密码'));
                } else {
                    if (!passwords.test(value) &&!pattern.test(value) && !patterns .test(value) ) {
                        callback(new Error('必须包含字母.数字.特殊符号中的两种,且密码长度不能低于6位'));
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.ruleFormPass.pass) {
                    callback(new Error('密码不一致请重新输入!'));
                } else {
                    callback();
                }
            };
            var validateuser = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入用户名/手机号"));
                }else {
                    callback();
                }
            };
            var code = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error(this.$t('input_phone_code')));
                } else if (!codes.test(value)) {
                    callback(new Error('验证码输入有误'));
                } else {
                    callback();
                }
            };
            var validatecode = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入验证码"));
                } else if (this.ruleForm.code !== this.identifyCode) {
                    callback(new Error("验证码错误"));
                } else {
                    callback();
                }
            };
            return {
                active:0,
                disabled:false,
                ruleForm:{
                    userOrTel:'',
                    code:''
                },
                ruleFormRules: {
                    userOrTel: [{ validator: validateuser, trigger: "blur" }],
                    code: [{ validator: validatecode, trigger: "blur" }]
                },
                ruleFormMobile:{
                    phone_code:''
                },
                ruleFormMobileRules:{
                    phone_code:[{ validator: code, trigger: "blur" }]
                },
                ruleFormPass:{
                    pass:'',
                    checkpass:''
                },
                ruleFormPassRules:{
                    pass: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    checkpass: [
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                },
                identifyCode: " ",
                identifyCodes: "1234567890",
                username:'',
                mobileStr:'',
                mobilePrefix:'',
                token:''
            }
        },
        mounted(){
            this.identifyCode = "";
            this.makeCode(this.identifyCodes, 4);
        },
        methods:{
            submitOneForm(form){
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.getMobile();
                        return;
                    } else {
                        return false;
                    }
                });
            },
            submitSecondForm(form){
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.check_code();
                        return;
                    } else {
                        return false;
                    }
                });
            },
            submitThirdForm(form){
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.change_pwd();
                        return;
                    } else {
                        return false;
                    }
                });
            },
            // 生成随机数
            randomNum(min, max) {
                return Math.floor(Math.random() * (max - min) + min);
            },
            // 切换验证码
            refreshCode() {
                this.identifyCode = "";
                this.makeCode(this.identifyCodes, 4);
            },
            // 生成四位随机验证码
            makeCode(o, l) {
                for (let i = 0; i < l; i++) {
                    this.identifyCode += this.identifyCodes[
                        this.randomNum(0, this.identifyCodes.length)
                        ];
                }
            },
            getMobile(){
                let username = this.ruleForm.userOrTel;
                let that =this;
                this.axios
                    .post("/api/v1/user/get_mobile", { username: username })
                    .then(res => {
                        if (res.data.status == "success") {
                            if(!res.data.data.mobile){
                                that.$message.error('手机号未绑定,请联系客服修改密码');
                                return;
                            }
                            this.active=1;
                            that.username=username;
                            that.mobilePrefix = res.data.data.mobile_prefix;
                            that.mobileStr = that.mobilePrefix+res.data.data.mobile;
                          } else {
                            let _msg = res.data.msg;
                            that.refreshCode();
                            that.ruleForm.userOrTel='';
                            that.ruleForm.code='';
                            return this.$message(_msg);
                        }
                    })
                    .catch(res => {
                        // let _msg =res.data.msg;
                        // return this.$message(_msg);
                    });
            },
            check_code() {
                let code = this.ruleFormMobile.phone_code;
                this.axios
                    .post("/api/v1/user/check_code_by_username", {
                        username: this.username,
                        code: code
                    })
                    .then(res => {
                        if (res.data.status == 'success') {
                            this.active=2;
                             this.token = res.data.data.token;
                            // this.$router.push({
                            //     name: 'set_password', params: {
                            //         token: this.token,
                            //         code: code, username: this.username
                            //     }
                            // })
                            return;
                        } else {
                            return this.$message(res.data.msg);
                        }
                    })
                    .catch(res => {
                        console.log(res.data);
                    });
            },
            change_pwd(){
                this.axios
                    .post("/api/v1/user/change_password ", {
                        username: this.username,
                        password :this.ruleFormPass.pass,
                        token :this.token,
                        code:this.ruleFormMobile.phone_code,
                    })
                    .then(res => {
                        if (res.data.status=='success') {
                            this.$router.push({name:'login'});
                            return;
                        } else {
                            return this.$message(res.data.msg);
                        }
                    })
                    .catch(res => {
                        console.log(res.data);
                    });
            }
        }
    }
</script>

<style scoped lang="scss">
.r-contain{
   padding-top: 100px;
    .r-c-c{
        width: 290px; margin: 0px auto; padding: 20px 60px;box-shadow: 0 4px 10px 0 #cbd2db;
    }
}
</style>
